<?php

interface DomArIdGenerator {
	
	public function acquire( DomArDomainObject $object );
	
	public function registerNewGroup( $groupName );
	
	public function createTable();
	
	
}

/*
 * Generates and manages unique ID-s for objects.
 * 
 * NB! Must connect to database within another transaction than actual unit of work commit.
 * 
 * @author Oliver Leisalu
 * @package DomAr
 */
class DomArIdGeneratorGrouped implements DomArIdGenerator {

	/**
	 * Name of the table where id values are held.
	 *
	 * @var String
	 */
	private $tableName = 'domar_id_map';
	/**
	 * Id values cache.
	 *
	 * @var Array
	 */
	private $cache = array();
	/**
	 * Database session name
	 * @var String
	 */
	private $databaseSessionName;
	
	/**
	 * @param String $tableName
	 */
	public function setTableName( $tableName ) {
		$this->tableName = $tableName;
	}
	/**
	 * @param String $databaseSessionName
	 */
	public function setDatabaseSessionName( $databaseSessionName ) {
		$this->databaseSessionName = $databaseSessionName;
	}
	/**
	 * Acquire id for domain object
	 *
	 * @param DomArDomainObject $object
	 * @return Int
	 */
	public function acquire( DomArDomainObject $object ) {
		
		$groupName = $object->getIdGroupName();
		
		if( $this->cache[$groupName][1] == 0 ) {
			DomSql::query( 'UPDATE `'.$this->tableName.'` SET `index` = LAST_INSERT_ID(`index` + '.(int)$incrementBy.');', $this->databaseSessionName );
		
			$n = (int)DomSql::selectOneQuery('SELECT LAST_INSERT_ID() as n','n', $this->databaseSessionName);
		
			$this->cache[$keyName] = array($n, (int)$incrementBy);
		}
		
		$this->cache[$groupName][1]--;
		
		return $this->cache[$groupName][0] - $this->cache[$groupName][1];
	}
	/**
	 * Registeres new key to database
	 *
	 * @param String $groupName
	 * @return Bool true on sucess, false on failure
	 */
	public function registerNewGroup( $groupName ) {
		try {
			DomSql::query('INSERT INTO `'.$this->tableName.'` (keyName) VALUES (\''.addslashes($keyName).'\')', $this->databaseSessionName);
		} catch (Exception $e ) {
			return false;
		}
		return true;
	}
	/**
	 * Create key indexes table.
	 */
	public function createTable() {
		DomSql::query('CREATE TABLE `'.$this->tableName.'` ( 
			keyName char(60) PRIMARY KEY, 
			`index` int(11) NOT NULL DEFAULT 0
		)', $this->databaseSessionName);
	}
	
}


class DomArIdGeneratorDefault implements DomArIdGenerator {
	
	public function acquire( DomArDomainObject $object ) {
		return 0;
	}
	
	public function registerNewGroup( $groupName ) {
		return true;
	}
	
	public function createTable() {
		
	}
	
	
}
?>